﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CustomerEmailer.Common;
using System.IO;

namespace CustomerEmailer
{
    public class Logger
    {
        private string LogFile
        {
            get
            {
                return Utils.GetSetting("LogFile");
            }
        }

        public void Log(string userName, string email, string messageTitle, string messageContent, int numberOfAttachedFiles)
        {
            var logBuilder = new StringBuilder();
            logBuilder.AppendFormat("*************************************");
            logBuilder.AppendLine();
            logBuilder.AppendFormat("שם משתמש:   {0}", userName);
            logBuilder.AppendLine();
            logBuilder.AppendFormat("כתובת מייל:   {0}", email);
            logBuilder.AppendLine();
            logBuilder.AppendFormat("כותרת הודעה:   {0}", messageTitle);
            logBuilder.AppendLine();
            logBuilder.AppendFormat("מספר קבצים מקושרים:   {0}", numberOfAttachedFiles);
            logBuilder.AppendLine();
            logBuilder.AppendFormat("תאריך:   {0}", DateTime.Now);
            logBuilder.AppendLine();
            logBuilder.Append("-------------------------------------------");
            WriteToLog(logBuilder.ToString(), LogFile);
        }

        public void Log(string filename, string content)
        {
            var logBuilder = new StringBuilder();
            logBuilder.Append(content);
            logBuilder.AppendLine();
            logBuilder.Append("-------------------------------------------");
            WriteToLog(logBuilder.ToString(),filename);
        }

        void WriteToLog(string content,string filename)
        {
            StreamWriter log = null;
            if (!File.Exists(filename))
            {
                var stream = File.Create(filename);
                log = new StreamWriter(stream);
            }
            else
            {
                log = File.AppendText(filename);
            }
            log.WriteLine(content);
            log.Close();
        }

        public static string readLog()
        {
            StreamReader log = null;
            log = File.OpenText(Utils.GetSetting("LogFile"));
            string res = log.ReadToEnd();
            log.Close();
            return res;
        }
    }
}
